<template>
  <CompOperate
      :field="field"
      :designer="designer"
      :design-state="designState"
      :parent-list="parentList"
      :parent-widget="parentWidget"
      :sub-form-row-id="subFormRowId"
      :sub-form-row-index="subFormRowIndex"
      :sub-form-col-index="subFormColIndex"
      :index-of-parent-list="indexOfParentList"
      :display-style="field['options'].displayStyle"
  >
    <div class="scene-waiting-row-queue-widget" :style="getStyle('area')">
      <div class="widget-wrap" :style="getStyle('widgetWrap')">
        <div class="queue-view" ref="resize"
             :data-state="queueScrollState(waitQueueInfo)? '滚动':'静止'">

          <!--静态-->
          <template v-if="!queueScrollState(waitQueueInfo)">
            <template v-for="(item,key) in waitQueueFillInfo">
              <div class="child-item" :key="key">
                <div class="queue-name item" :style="getStyle('queueName')">
                  <ScrollX>
                    {{ getQueueName(item) }}
                  </ScrollX>
                </div>
                <div class="patient-name item" :style="getStyle('patientName')">
                  <ScrollX>{{ getCurrentPatient(item) }}</ScrollX>
                </div>
              </div>
            </template>
          </template>

          <!--滚动-->
          <template v-else>
            <template v-if="!!waitQueueInfo?.length">
              <vue-seamless-scroll
                  :key="`${widgetKey}`"
                  ref="scroll"
                  class="queue-scroll-info"
                  @ScrollEnd="handleScrollEnd"
                  :data="waitQueueInfo"
                  :class-option="queueScrollOption(waitQueueInfo)"
              >
                <div class="inside-content-info">
                  <template class="patient-info" v-for="(item,key) in waitQueueInfo">
                    <div class="child-item-info" :key="`${widgetKey}_${key}`" v-if="true">
                      <div class="queue-name-info item-info" :style="getStyle('queueName')">
                        {{ key + 1 }}{{ getQueueName(item) }}
                      </div>
                      <div class="patient-name-info item-info" :style="getStyle('patientName')">
                        {{ getCurrentPatient(item) }}
                      </div>
                    </div>
                  </template>
                </div>
              </vue-seamless-scroll>
            </template>
          </template>
        </div>
      </div>
    </div>
  </CompOperate>
</template>

<script>
import {v4 as uuid} from 'uuid';
import {pxToVw} from "@/utils/common";
import emitter from "@/utils/designer/emitter";
import {buildParentApi} from "@/utils/designer/util";
import vueSeamlessScroll from 'vue-seamless-scroll';
import ScrollX from '@c/public/seamlessScroll/ScrollX.vue'
import ScrollEditX from '@c/public/seamlessScroll/ScrollEditX.vue'
import mixin from "@sc/templateDetails/modules/homeMiddle/fieldMixin";
import CompOperate from "@c/public/form-designer/devType/modules/compOperate.vue";

let buildParent = buildParentApi();
export default {
  name: "scene-waiting-row-queue-widget",

  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件

  mixins: [emitter, mixin],

  props: {
    widget: Object,
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
    designState: {
      type: Boolean,
      default: false,
    },
    devType: {
      type: Boolean,
      default: false,
    },
    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },

    headTitle: {
      type: String,
      default: "",
    },
    visibleTitle: {
      type: Boolean,
    },
  },

  components: {
    ScrollX,
    CompOperate,
    ScrollEditX,
    vueSeamlessScroll
  },

  data() {
    return {
      firstUpdated: false,
      widgetKey: uuid(),
      optionsInfo: Object(),
    }
  },

  computed: {
    // 设置的各元素的行内样式
    getStyle() {
      return function (val) {
        const self = this;
        let info = (self.optionsInfo) || Array();
        let Obj = Object();
        switch (val) {
          case "area":
            Reflect.set(Obj, "height", pxToVw(info.viewHeight));
            return Obj;
          case "widgetWrap":
            Reflect.set(Obj, "paddingTop", pxToVw(info.padding.top));
            Reflect.set(Obj, "paddingBottom", pxToVw(info.padding.bottom));
            return Obj;
          case "queueName":
            Reflect.set(Obj, "fontWeight", (info.queueFontWeight));
            Reflect.set(Obj, "fontSize", pxToVw(info.queueFontSize));
            Reflect.set(Obj, "color", (info.queueFontColor));
            Reflect.set(Obj, "backgroundColor", (info.queueBackgroundColor));
            return Obj;
          case "patientName":
            Reflect.set(Obj, "fontWeight", (info.patientFontWeight));
            Reflect.set(Obj, "fontSize", pxToVw(info.patientFontSize));
            Reflect.set(Obj, "color", (info.patientFontColor));
            Reflect.set(Obj, "backgroundColor", (info.patientBackgroundColor));
            return Obj;
        }
      };
    },


    // 队列滚动的设置项目
    queueScrollOption() {
      return function (row) {
        let {scrollState, scrollStep, scrollNumber} = (this.optionsInfo);
        let state = scrollState && (row?.length > scrollNumber) && (this.widgetKey);
        return {
          step: [1, 1.5, 2, 2.5, 3][scrollStep - 1], // 数值越大速度滚动越快
          hoverStop: true,
          direction: 2, // 0向下 1向上 2向左 3向右
          limitMoveNum2: state ? scrollNumber : 99999, // 开始无缝滚动的数据量 this.dataList.length
          limitMoveNum: 5, // 开始无缝滚动的数据量 this.dataList.length
        };
      }
    },

    // 队列是否滚动
    queueScrollState() {
      return function (row) {
        let {scrollState, scrollNumber} = (this.optionsInfo);
        return scrollState && (row?.length >= scrollNumber);
      }
    },

    getQueueName() {
      return function (row) {
        let {
          queueName,
          deptNameKey = 'deptName',
          roomNameKey = 'treatmentRoomName',
          registerNameKey = 'registerObjName'
        } = this.optionsInfo;
        switch (queueName) {
          case 'roomNo':
            return row['roomNo'] || '\u00a0'
          case 'roomName':
            return row[roomNameKey] || '\u00a0'
          case 'deptName':
            return row[deptNameKey] || '\u00a0'
          case 'registerName':
            return row[registerNameKey] || '\u00a0'
        }
      }
    },

    // 列表的队列的患者(原始)
    waitQueueInfo() {
      let devType = (this.devType);
      let queueListInfo = this.$store.getters['getWaitingQueueListInfo'];
      return devType ? queueListInfo.apiData : queueListInfo.mockData;
    },

    waitQueueFillInfo() {
      let {switchCol} = this.optionsInfo;
      let queueInfo = this.waitQueueInfo || Array();
      if (queueInfo.length >= switchCol) {
        return queueInfo.slice(0, switchCol)
      } else {
        let fillArr = Array(switchCol - queueInfo.length).fill({});
        return [...queueInfo, ...fillArr]
      }
    },


    // 当前就诊的患者|| 医生暂停接诊
    getCurrentPatient() {
      return function (val) {
        /**
         * 在线状态 0在线 1暂停 2退出
         **/
        const self = this;
        let type = parseInt(val.onlineStatus);
        switch (type) {
          case 0:
          case 2:
            if (!!(val?.treatingPatient?.length)) {
              let currentPatient = Array();
              (val.treatingPatient).forEach((item) => {
                let orderNo = item?.orderNo;
                let patientOrderNoInfo = '';
                if (!!orderNo) {
                  patientOrderNoInfo = `${(item.orderNo) || '\u00a0'}`;
                }
                let temp = `${patientOrderNoInfo} ${(item.patientName) || '\u00a0'}`
                currentPatient.push(temp)
              })
              return (self.$lodash.join(currentPatient, ' '));
            } else {
              return '\u00a0'
            }
          case 1:
            return '暂停接诊';
        }
      }
    },

  },

  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop 需要在父组件created中初始化！！ */
    this.registerToRefList();
    this.initEventHandler();
    this.handleOnCreated();
  },

  mounted() {
    this.handleOnMounted();
    this.observeWithResizeObserver();
  },

  methods: {
    // 接收父组件传递过来的数据
    executeMethod(key, data) {
      switch (key) {
        case "refreshData":
          let queueListInfo = this.$lodash.cloneDeep(data);
          this.$store.dispatch('setWaitingQueueListInfo', queueListInfo)
          break
        case "patientListInfo":
          let patientList = this.$lodash.cloneDeep(data);
          this.$store.dispatch('setWaitingPatientInfo', patientList)
          break
      }
    },

    handleScrollEnd() {
      console.log('滚动结束')
      this.widgetKey = uuid();
    },

    // 监听视图变化
    observeWithResizeObserver() {
      const self = this;
      const element = self.$refs.resize;
      let number;
      const observer = new ResizeObserver(entries => {
        entries.forEach(entry => {
          if (number !== entry.contentRect.width) {
            number = entry.contentRect.width;
            self.widgetKey = uuid();
          }
        });
      });
      observer.observe(element);

      // 销毁时移除监听
      this.$once('hook:beforeDestroy', () => {
        observer.disconnect();
      });
    }

  },

  watch: {
    field: {
      handler: function (val) {
        this.widgetKey = uuid();
        let key = (val.options.config);
        this.optionsInfo = (val.options[key]);
      },
      deep: true,
      immediate: true
    }
  },

  destroyed() {
    this.unregisterFromRefList();
  },

};
</script>

<style lang="scss" scoped>

.scene-waiting-row-queue-widget {
  background-color: transparent;
  display: flex;
  flex-direction: row;
  margin: 0 28px 0 28px;
  box-sizing: border-box;
  overflow: hidden;

  .widget-wrap {
    background-color: transparent;
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
    color: #333;
    overflow: hidden;
    box-sizing: border-box;
  }

  //顶部队列
  .queue-view {
    //height: 100%;
    //width: 100%;
    //flex-shrink: 0;
    //overflow: hidden;
    //display: flex;
    //justify-content: space-between;
    //flex-direction: row;

    .child-item {
      display: flex;
      flex-direction: column;
      flex-grow: 1;
      margin-right: 10px;
      margin-left: 10px;
      flex-shrink: 0;
      flex-basis: 0;
      background: rgba(0, 71, 143, 1);
      border-radius: 16px;
      overflow: hidden;
      color: #FFFFFF;
      font-size: 50px;
      box-sizing: border-box;


      &:last-child {
        margin-right: 0;
      }

      &:first-child {
        margin-left: 0;
      }


      .item {
        display: flex;
        width: 100%;
        justify-content: center;
        align-self: center;
        align-items: center;
      }

      .queue-name {
        height: 90px;
      }

      .patient-name {
        font-size: 54px;
        height: calc(100% - 90px);
        background: rgba(4, 88, 179, 1);
      }
    }
  }

  :deep(.queue-scroll-info) {
    width: 100%;
    height: 100%;

    > div {
      display: flex;
      height: 100%;
      flex-direction: row;
    }

    .inside-content-info {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      height: 100%;
      box-sizing: border-box;
      white-space: nowrap;

      .child-item-info {
        //margin-right: 10px;
        //margin-left: 10px;
        //background: rgba(0, 71, 143, 1);
        //border-radius: 16px;
        //color: #FFFFFF;
        //font-size: 50px;
        //display: inline-block;
        //flex-shrink: 0;
        //width: 352px;
        //min-width: inherit;
        //max-width: inherit;
        //overflow: hidden;
        //box-sizing: border-box;

        .item-info {
          display: flex;
          width: 100%;
          justify-content: center;
          align-self: center;
          white-space: nowrap;
          align-items: center;
        }

        .queue-name-info {
          height: 90px;
          text-align: center;
          line-height: 90px;
          overflow: hidden;
        }

        .patient-name-info {
          font-size: 54px;
          height: calc(100% - 90px);
          white-space: nowrap;
          background: rgba(4, 88, 179, 1);
        }
      }
    }
  }
}
</style>